<template>
  <t-link theme="primary" @click="visible = true">
    查看预览
  </t-link>
  <t-dialog
    v-model:visible="visible"
    attach="body"
    :close-on-overlay-click="false"
    :confirm-btn="null"
    destroy-on-close
    header=""
    width="80%"
    placement="top"
    top="40px"
    @opened="handleDialogOpened"
  >
    <div id="excel" style="width: 100%;height: 700px;" ref="excel"></div>
  </t-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import jsPreviewExcel from "@js-preview/excel";
import '@js-preview/excel/lib/index.css';

// 定义 fileUrl 的类型
interface FileItem {
  raw?: Record<string, any>;
  url: string;
  name?: string;
  size?: number;
  type?: string;
  status?: string;
  percent?: number;
  response?: { url: string };
  uploadTime?: string;
  lastModified?: number;
}

const props = defineProps({
  fileUrl: {
    type: Array as () => FileItem[],
    default: () => [],
  },
});

const visible = ref(false);
const excel = ref<HTMLElement | null>(null);
let myExcelPreviewer: any = null;

const initExcelPreviewer = () => {
  if (!excel.value || !props.fileUrl.length) return;
  
  myExcelPreviewer = jsPreviewExcel.init(excel.value);
  myExcelPreviewer.preview(props.fileUrl[0].url)
    .then(() => console.log('预览完成'))
    .catch((e: any) => console.log('预览失败', e));
};

const handleDialogOpened = () => {
  initExcelPreviewer();
};

// Clean up when component unmounts
onMounted(() => {
  return () => {
    if (myExcelPreviewer) {
      myExcelPreviewer.destroy();
    }
  };
});
</script>